<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
  console.log('Page loaded');

  var NO_LINK_EXCEPTION = 'No Chrome Web Store item link found.';
  var INVALID_URL_EXCEPTION = 'Invalid Chrome Web Store item URL.';

  function checkNoLinkFound(expectedException, opt_preferredStoreUrl) {
    console.log('Expecting exception: ' + expectedException);
    try {
      chrome.webstore.install(opt_preferredStoreUrl);
      console.log('Exception should have been thrown');
      window.domAutomationController.send(false);
    } catch (err) {
      if (err != expectedException) {
        console.log('Unexpected exception thrown: ' + err);
        window.domAutomationController.send(false);
      }
    }
  }

  function runTest(galleryUrl) {
    console.log('In runTest');

    // Definitely no link.
    checkNoLinkFound(NO_LINK_EXCEPTION);

    // Empty link.
    var linkNode = document.createElement('link');
    document.getElementsByTagName('head')[0].appendChild(linkNode);
    checkNoLinkFound(NO_LINK_EXCEPTION);

    // Wrong type, right URL.
    linkNode.rel = 'alternate';
    linkNode.href = galleryUrl + '/detail/mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm';
    checkNoLinkFound(NO_LINK_EXCEPTION);

    // Right type, wrong URL.
    linkNode.rel = 'chrome-webstore-item';
    linkNode.href = 'http://app.com/detail/abc';
    checkNoLinkFound(INVALID_URL_EXCEPTION);

    // Non-item CWS URL
    linkNode.href =
        galleryUrl + '/someotherpage/mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm';
    checkNoLinkFound(INVALID_URL_EXCEPTION);

    // Invalid ID
    linkNode.rel = 'chrome-webstore-item';
    linkNode.href = galleryUrl + '/detail/abc';
    checkNoLinkFound(INVALID_URL_EXCEPTION);

    // Extra CWS URL parameters
    linkNode.href =
        galleryUrl + '/detail/mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm?foo=bar';
    checkNoLinkFound(INVALID_URL_EXCEPTION);

    // Non-existent preferred link.
    linkNode.rel = 'chrome-webstore-item';
    linkNode.href = galleryUrl + '/detail/mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm';
    checkNoLinkFound(
        NO_LINK_EXCEPTION,
        galleryUrl + '/detail/iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii');

    console.log('Ran all tests, sending response');

    // Successful installation is tested elsewhere
    window.domAutomationController.send(true);

    console.log('Test complete');
  }
</script>

</body>
</html>
